package com.hbk.gen;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.utility.StringUtil;

public class Application {
	
	private static Configuration freemarkerCfg = new Configuration();
	
	public static void main(String[] args) {
		buildModular();
	}

	private static void buildModular() {
		try {
			Context context=new Context();
			File file=new File("src/main/resources/gen/json/pojo");
			File[] files=file.listFiles();
			for(File f:files) {
				String json=FileUtils.readFileToString(f, "UTF-8");
				Pojo pojo=JSON.parseObject(json, new TypeReference<Pojo>() {});
				buildFile("modular/ftl/entity.ftl","src\\main\\resources\\gen\\output\\java\\com\\hbk\\pojos\\"+pojo.getClazz()+".java",pojo,"UTF-8");
				context.getPojos().add(pojo);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void buildFile(String templateName, String fileName, Object obj,String encoding) throws Exception {
		try {
			freemarkerCfg.setClassForTemplateLoading(Application.class, "/");
			freemarkerCfg.setEncoding(Locale.getDefault(), encoding);
			Template template = freemarkerCfg.getTemplate(templateName);
			template.setEncoding("UTF-8");
			File htmlFile = new File(fileName);
			htmlFile.getParentFile().mkdirs();
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), encoding));
			template.process(obj, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
